/**
 * moieo.net
 * @author Moieo
 */
package cn.moieo.carcontrol.view

import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@Preview
@Composable
fun StateView(
    size: Dp = 24.dp,
    color: Color = Color.Red,
    fontColor: Color = Color.White,
    fontSize: TextUnit = 24.sp,
    transparent: Float = 1f,
    text: String? = null,
    flash: Boolean = false
) {
    val transition = rememberInfiniteTransition()
    val alpha by transition.animateFloat(
        initialValue = transparent, targetValue = 0.35f, animationSpec = infiniteRepeatable(
            animation = tween(durationMillis = 500), repeatMode = RepeatMode.Reverse
        )
    )
    Box(
        modifier = Modifier
            .size(size)
            .padding(2.dp)
            .graphicsLayer(alpha = if (flash) alpha else transparent),
        contentAlignment = Alignment.Center
    ) {
        Canvas(modifier = Modifier.size(size)) {
            // 计算圆心位置和半径
            val canvasWidth = this.size.width
            val canvasHeight = this.size.height
            val radius = (canvasWidth.coerceAtMost(canvasHeight)) / 2f

            drawCircle(
                color = color,
                center = Offset(x = canvasWidth / 2, y = canvasHeight / 2),
                radius = radius,
                style = Fill
            )
        }
        if (text != null) {
            Text(
                text = text, style = TextStyle(
                    color = fontColor, fontSize = fontSize, fontWeight = FontWeight.Normal
                )
            )
        }
    }
}